package com.sn.system.common.validator.validators;

import java.io.UnsupportedEncodingException;

import com.sn.system.common.utils.CheckUtils;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class StringByteFieldValidator extends FieldValidatorSupport{

	private String maxLength;
	public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object value = this.getFieldValue(fieldName, object);
        // if there is no value - don't do comparison
        // if a value is required, a required validator should be added to the field
        if (value == null) {
            return;
        }
        
        // XW-375 - must be a string
        if (!(value instanceof String)) {
            return;
        }

        // string must not be empty
        String str = ((String) value).trim();
        if (str.length() == 0) {
            return;
        }
        if(CheckUtils.isNumber(getMaxLength())){
       	 try {
       		 int length=str.getBytes("Windows-31J").length;
			if(length>Integer.parseInt(getMaxLength())){
			    	addFieldError(getFieldName(), object);
			    }
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
       }
	}
	public String getMaxLength() {
		return maxLength;
	}
	public void setMaxLength(String maxLength) {
		this.maxLength = maxLength;
	}

	
}
